package com.sojson.project.tool.gen.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.code.gen.CodeGenRun;
import com.code.gen.bean.bo.CodeGenProperties;
import com.code.gen.bean.bo.CodeGenPropertiesSystem;
import com.sojson.project.tool.gen.entity.dto.GenTableDto;
import com.sojson.project.tool.gen.entity.dto.GenTablePageDto;
import com.sojson.project.tool.gen.entity.po.GenTable;
import com.sojson.project.tool.gen.entity.vo.GenTableVo;
import com.sojson.project.tool.gen.service.GenTableService;
import com.sojson.result.Result;
import com.sojson.util.StringUtil;
import com.sojson.util.poi.ExcelUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 代码生成业务表控制器
 * 
 * @author liu
 * @date 2022-10-28
 */
@Api(tags = "代码生成业务表管理")
@RestController
@RequestMapping("/tool/gen/table")
public class GenTableController {

    @Autowired
    private GenTableService genTableService;

    /**
     * 单条插入
     * 
     * @param dto
     * @return
     */
    @PostMapping("/save")
    @PreAuthorize("@ss.hasPermi('/tool/gen/table/save')")
    @ApiOperation("给代码生成业务表添加一条数据")
    public Result<Boolean> save(@RequestBody GenTable dto) {
        return Result.success(genTableService.save(dto));
    }

    /**
     * 通过iD更新
     * 
     * @param dto
     * @return
     */
    @PutMapping("/updateById")
    @PreAuthorize("@ss.hasPermi('/tool/gen/table/updateById')")
    @ApiOperation("通过iD更新代码生成业务表数据")
    public Result<Boolean> updateById(@RequestBody GenTableDto dto) {
        String parentMenuId = dto.getParentMenuId();
        if (StringUtil.isBlankString(parentMenuId)) {
            dto.setParentMenuId(new CodeGenPropertiesSystem().getParentMenuId());
        }
        return Result.success(genTableService.update(dto));
    }

    /**
     * 列表查询
     * 
     * @param dto
     * @return
     */
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('/tool/gen/table/list')")
    @ApiOperation(value = "查询代码生成业务表数据", response = GenTableVo.class)
    public Result<List<GenTableVo>> list(GenTableDto dto) {
        return Result.success(genTableService.list(dto));
    }

    /**
     * 分页查询
     * 
     * @param dto
     * @return
     */
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPermi('/tool/gen/table/page')")
    @ApiOperation(value = "分页查询代码生成业务表数据", response = GenTableVo.class)
    public Result<List<GenTableVo>> page(GenTablePageDto dto) {
        return Result.success(genTableService.page(dto));
    }

    /**
     * 导出数据
     * 
     * @param dto
     * @return
     * @throws Exception 
     */
    @GetMapping("/export")
    @PreAuthorize("@ss.hasPermi('/tool/gen/table/export')")
    @ApiOperation("导出代码生成业务表数据")
    public void export(GenTableDto dto) throws Exception {
        List<GenTableVo> list = genTableService.list(dto);
        ExcelUtil<GenTableVo> excelUtil = new ExcelUtil<>(GenTableVo.class);
        excelUtil.exportExcelOutFile(list, "代码生成业务表");
    }

    /**
     * 通过iD查询
     * 
     * @param id
     * @return
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("@ss.hasPermi('/tool/gen/table/info/{id}')")
    @ApiOperation(value = "通过iD查询代码生成业务表数据", response = GenTableVo.class)
    public Result<GenTableVo> info(@PathVariable String id) {
        if (id == null) {
            return Result.success();
        }

        Result<GenTableVo> success = Result.success();
        GenTableVo findById = genTableService.findById(id);
        success.setData(findById);
        return success;
    }

    /**
     * 通过id列表删除
     * 
     * @param dto
     * @return
     */
    @DeleteMapping("/remove")
    @PreAuthorize("@ss.hasPermi('/tool/gen/table/remove')")
    @ApiOperation("通过iD列表删除代码生成业务表数据")
    public Result<Boolean> remove(@RequestBody GenTableDto dto) {
        List<String> ids = dto.getIds();
        if (ids == null || ids.size() == 0) {
            return Result.success();
        }

        return Result.success(genTableService.removeByIds(ids));
    }

    /**
     * 清空数据
     * 
     * @return
     */
    @DeleteMapping("/clear")
    @PreAuthorize("@ss.hasPermi('/tool/gen/table/clear')")
    @ApiOperation("清空代码生成业务表数据")
    public Result<Boolean> clear() {
        return Result.success(genTableService.clear());
    }

    /**
     * 通过iD删除
     * 
     * @param id
     * @return
     */
    @DeleteMapping("/remove/{id}")
    @PreAuthorize("@ss.hasPermi('/tool/gen/table/remove/{id}')")
    @ApiOperation("通过iD删除代码生成业务表数据")
    public Result<Boolean> remove(@PathVariable String id) {
        if (id == null) {
            return Result.success();
        }

        return Result.success(genTableService.removeById(id));
    }

    /**
     * 从数据库获取表信息
     * 
     * @param dto
     * @return
     */
    @GetMapping("/db/page")
    @PreAuthorize("@ss.hasPermi('/tool/gen/table/db/page')")
    @ApiOperation(value = "从数据库获取表信息", response = GenTableVo.class)
    public Result<List<GenTableVo>> dbPage(GenTablePageDto dto) {
        List<GenTableVo> dbPage = genTableService.dbPage(dto);
        return Result.success(dbPage);
    }

    /**
     * 导入表结构
     * 
     * @param dto
     * @return
     * @throws IOException
     */
    @PostMapping("/importTable")
    @PreAuthorize("@ss.hasPermi('/tool/gen/table/importTable')")
    @ApiOperation(value = "导入表结构", response = GenTableVo.class)
    public Result<Boolean> importTableSave(@RequestBody GenTableDto dto) throws IOException {
        List<String> tableNames = dto.getTableNames();
        if (tableNames == null || tableNames.size() == 0) {
            return Result.success();
        }

        // 查询表信息
        List<GenTableVo> dbList = genTableService.dbList(dto);
        genTableService.importGenTable(dbList);
        return Result.success();
    }

    /**
     * 同步数据库
     * 
     * @param tableName
     * @return
     */
    @PutMapping("/synchDb/{tableName}")
    @PreAuthorize("@ss.hasPermi('/tool/gen/table/synchDb/{tableName}')")
    @ApiOperation(value = "同步数据库", response = GenTableVo.class)
    public Result<Boolean> synchDb(@PathVariable("tableName") String tableName) {
        genTableService.synchDb(tableName);
        return Result.success();
    }

    /**
     * 预览代码
     * 
     * @param dto
     * @return
     * @throws Exception 
     */
    @GetMapping("/previewCode/{tableName}")
    @PreAuthorize("@ss.hasPermi('/tool/gen/table/previewCode/{tableName}')")
    @ApiOperation(value = "预览代码", response = GenTableVo.class)
    public Result<Map<String, String>> previewCode(@PathVariable("tableName") String tableName)
        throws Exception {
        CodeGenProperties properties = new CodeGenProperties();
        CodeGenPropertiesSystem codeGenPropertiesSystem = new CodeGenPropertiesSystem();
        codeGenPropertiesSystem.setTables(new String[] {tableName});
        properties.setSystem(codeGenPropertiesSystem);
        Map<String, String> run = CodeGenRun.run(properties, true);
        return Result.success(run);
    }

    /**
     * 生成代码
     * 
     * @param dto
     * @return
     * @throws Exception 
     */
    @PostMapping("/genCode")
    @PreAuthorize("@ss.hasPermi('/tool/gen/table/genCode')")
    @ApiOperation(value = "生成代码", response = GenTableVo.class)
    public void genCode(@RequestBody GenTableDto dto) throws Exception {
        List<String> ids = dto.getIds();
        if (ids == null || ids.size() == 0) {
            return;
        }

        CodeGenProperties properties = new CodeGenProperties();
        CodeGenPropertiesSystem codeGenPropertiesSystem = new CodeGenPropertiesSystem();
        codeGenPropertiesSystem.setTables(ids.toArray(new String[0]));
        properties.setSystem(codeGenPropertiesSystem);
        CodeGenRun.run(properties);
    }

}